﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Drawing;
using System.IO;
using SdmxMl.Common;
using Telerik.WinControls;
using Telerik.WinControls.UI;

namespace SakeVar
{
    /// <summary>
    /// Class for display and managment of questionnaire in Grid view
    /// </summary>
    public class QuestGridCreator
    {
        private Font fontQid;

        private RadGridView gridView;
        private RadDropDownList comboListQuestid;
        private RadButton buttonNavigateQuestId;
        private ExcelDataReader.ExcelDataReader spreadsheetCode = null;

        #region Constructor

        public QuestGridCreator(RadGridView radGrid, RadDropDownList questComboList, RadButton butNavQuest )
        {
            comboListQuestid = questComboList;
            comboListQuestid.SelectedIndexChanged += new Telerik.WinControls.UI.Data.PositionChangedEventHandler(comboListQuestid_SelectedIndexChanged);
            
            buttonNavigateQuestId = butNavQuest;
            buttonNavigateQuestId.Click += new EventHandler(buttonNavigateQuestId_Click);

            gridView = radGrid;
            gridView.CellFormatting += new CellFormattingEventHandler(gridView_CellFormatting);
            gridView.ToolTipTextNeeded += new ToolTipTextNeededEventHandler(gridView_ToolTipTextNeeded);
            fontQid = new Font("Courrier New", 8f, FontStyle.Bold);
        }

        #endregion

        #region Navigation to QID

        void buttonNavigateQuestId_Click(object sender, EventArgs e)
        {
            string qid = comboListQuestid.Text;
            SelectRow(qid);
        }

        public void SelectRow(string qid)
        {
            for (int r = 0; r < gridView.RowCount; r++)
            {
                if (gridView.Rows[r].Cells["QID"].Value.ToString().Equals(qid))
                {
                    gridView.Rows[r].IsCurrent = true;
                    gridView.Rows[r].Cells[0].IsSelected = true;
                   // gridView.Rows[r].EnsureVisible();
                    gridView.TableElement.ScrollToRow(gridView.Rows[r]); 
                    break;
                }
            }
        }

        void comboListQuestid_SelectedIndexChanged(object sender, Telerik.WinControls.UI.Data.PositionChangedEventArgs e)
        {
            buttonNavigateQuestId_Click(comboListQuestid, EventArgs.Empty);
        }

        #endregion

        #region ToolTip needed Event

        private void gridView_ToolTipTextNeeded(object sender, Telerik.WinControls.ToolTipTextNeededEventArgs e)
        {
            GridDataCellElement dataCell = sender as GridDataCellElement;

            if (dataCell != null)
            {
                TextPart textPart = new TextPart(dataCell);
                SizeF size = textPart.Measure(new SizeF(float.PositiveInfinity, float.PositiveInfinity));
                SizeF sizeInCell = textPart.Measure(new SizeF(dataCell.ColumnInfo.Width, float.PositiveInfinity));

                string toolTipText = null;

                float cellWidth = dataCell.ColumnInfo.Width - dataCell.BorderWidth * 2;
                float cellHeight = dataCell.Size.Height - dataCell.BorderWidth * 2;

                if (size.Width > cellWidth || cellHeight < sizeInCell.Height)
                {
                    toolTipText = dataCell.Text;
                }

                e.ToolTipText = toolTipText;
            }
        }
        #endregion

        #region Cell formatting Event

        void gridView_CellFormatting(object sender, CellFormattingEventArgs e)
        {
            if (e.CellElement.RowInfo.Cells["No"].Value != null && e.CellElement.RowInfo.Cells["No"].Value.ToString() == "01")
            {
                if (e.CellElement.ColumnInfo.Name == "QID")
                {
                    e.CellElement.Font = fontQid;
                }
                else
                {
                    e.CellElement.ResetValue(LightVisualElement.FontProperty, ValueResetFlags.Local);
                    e.CellElement.DrawFill = true;
                    e.CellElement.BackColor = Color.LightCoral;
                    e.CellElement.GradientStyle = Telerik.WinControls.GradientStyles.Solid;
                }

            }
            else
            {
                e.CellElement.ResetValue(LightVisualElement.DrawFillProperty, Telerik.WinControls.ValueResetFlags.Local);
                e.CellElement.ResetValue(VisualElement.BackColorProperty, ValueResetFlags.Local);
                e.CellElement.ResetValue(LightVisualElement.GradientStyleProperty, ValueResetFlags.Local);
                e.CellElement.ResetValue(LightVisualElement.FontProperty, ValueResetFlags.Local);
            }
        }
        #endregion

        #region Grid Columns construction

        private ExcelDataReader.ExcelDataReader LoadSources(string propertyPath)
        {
            ExcelDataReader.ExcelDataReader spreadsheet = null;
            if (propertyPath == null)
                throw new ApplicationException("Please provides path.");

            FileStream fs = null;
            try
            {
                fs = new FileStream(propertyPath, FileMode.Open, FileAccess.Read, FileShare.Read);
                spreadsheet = new ExcelDataReader.ExcelDataReader(fs);
            }
            finally
            {
                if (fs != null)
                    fs.Close();
            }

            return spreadsheet;
        }

        public void LoadGridData(string workSheetId, string excelPath)
        {
            using (new SdmxMl.Helper.CWaitCursor())
            {
                string sheetId = workSheetId + LangSupport.CurLang.Substring(0, 1).ToUpper();
                // Questionnaire already loaded fit demand of workbook ?
                if (spreadsheetCode != null)
                    if (spreadsheetCode.WorkbookData.Tables.Contains(sheetId) == false)
                        spreadsheetCode = null;

                if (spreadsheetCode == null)
                    spreadsheetCode = LoadSources(excelPath);

                // Now must contain sheet
                if (spreadsheetCode.WorkbookData.Tables.Contains(sheetId) == false)
                    throw new ApplicationException("Unable to locate sheet: " + sheetId + " in excel document.");

                DataTable dt = spreadsheetCode.WorkbookData.Tables[workSheetId + LangSupport.CurLang.Substring(0, 1).ToUpper()];
                if (dt.Rows[0][0].ToString()[0] != '0')
                {
                    dt.Columns[0].ColumnName = "QID";
                    dt.Columns[1].ColumnName = "No";
                    dt.Columns[2].ColumnName = "INFORMATION";
                    dt.Rows.RemoveAt(0);
                }


                gridView.BeginUpdate();
                gridView.DataSource = dt;
                gridView.AutoSizeColumnsMode = GridViewAutoSizeColumnsMode.Fill;
                gridView.EnableFiltering = false;
                gridView.EnableAlternatingRowColor = false;

                gridView.MasterTemplate.Columns[0].Width = 45;
                gridView.MasterTemplate.Columns[0].AllowResize = false;

                gridView.MasterTemplate.Columns[1].Width = 26;
                gridView.MasterTemplate.Columns[1].AllowResize = false;
                gridView.EndUpdate();

                gridView.MasterTemplate.AllowColumnChooser = false;

            }

        }
        #endregion


        public List<string> GetQidList(string questIdDisplay)
        {
            List<string> listId = new List<string>();

            if (questIdDisplay != null && questIdDisplay.Length > 0)
            {
                // Get groups of questions
                string[] arrGrp = questIdDisplay.Split('_');

                foreach (string sRangeId in arrGrp)
                {
                    string[] arrSeparatorId = sRangeId.Split('/');
                    foreach (string sep in arrSeparatorId)
                    {
                        string[] arrIntervalId = sep.Split('-');
                        bool inInterval = false;
                        foreach (string inter in arrIntervalId)
                        {
                            GetId(listId, inter, inInterval);
                                inInterval = true;
                        }

                    }
                


                    /*
                    if (arrIntervalId.Length == 1)
                        arrIntervalId = sRangeId.Split('/');

                    // first question ID
                    // if perion found
                    string firstId = arrIntervalId[0];
                    string[] arr = firstId.Split('.');
                    if (arr.Length == 1)
                        listId.Add(arr[0].PadRight(5, '0'));
                    else
                    {
                        string s = arr[1].Length != 2 ? arr[1].Substring(0, 1) + "0" : arr[1];
                        s = arr[0] + s;
                        listId.Add(s.PadLeft(5, '0'));
                    }
                    //TODO: Now interval
                    if (arrIntervalId.Length > 1)
                    {
                        string end = arrIntervalId[arrIntervalId.Length - 1];
                    }*/
                }
            }
            comboListQuestid.Items.Clear();
            foreach (string s in listId)
                comboListQuestid.Items.Add(s);
            if (listId.Count > 0)
            {
                comboListQuestid.SelectedIndex = 0;
                buttonNavigateQuestId_Click(comboListQuestid, EventArgs.Empty);
            }
            

            return listId;
        }

        private void GetId( List<string> listId, string tag, bool interval)
        {

            // two char, if interval create all val
            if (tag.Length == 2)
            {
                if (interval)
                {
                    int start = Convert.ToInt32(listId[listId.Count-1].Substring(3, 2));
                    int end = Convert.ToInt32(tag);
                    string baseId = listId[listId.Count-1].Substring(0, 3);
                    for (int i = start + 1; i <= end; i++)
                    {
                        listId.Add(baseId + i.ToString().PadLeft(2, '0'));
                    }

                }
                else if (listId.Count > 0)
                    listId.Add(listId[listId.Count-1].Substring(0, 3) + tag);
            }
            else
            {
                string[] arr = tag.Split('.');
                if (arr.Length == 1)
                {
                    listId.Add(arr[0].PadRight(5, '0'));
                }
                else
                {
                    string s = arr[1].Length != 2 ? arr[1].Substring(0, 1) + "0" : arr[1];
                    s = arr[0] + s;
                    listId.Add(s.PadLeft(5, '0'));
                }

            }

            // 3, 4,5 chars without period, create new id

        }
    }

}
